<template>
    <el-card>
        <!-- <div class="container">
            <img src="/public/tag_2.png" alt="">
            <div class="tag">各题平均分</div>
        </div> -->
        <div ref="chart" style="width: 700px; height: 400px;"></div>
    </el-card>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import eventBus from '/eventBus';

const chart = ref(null);

// 图表数据
const xAxisData = ref([]);
const optionData = ref([]);

// 监听数据变化
watch(() => eventBus.state.averageScores, (newScores) => {
    convertType(newScores);
    nextTick(() => {
        initChart();
    });
}, { deep: true });

// 数据转换
const convertType = (scores) => {
    xAxisData.value = [];
    optionData.value = [];
    for (const score of scores) {
        xAxisData.value.push(score.question);
        optionData.value.push(score.avg);
    }
}

// 初始化图表
const initChart = () => {
    const myChart = echarts.init(chart.value);
    const option = {
        title: {
            text: '各题平均分',
            left: 'center',
            top: 20,
            textStyle: {
                color: 'black'
            }
        },
        xAxis: {
            type: 'category',
            data: xAxisData.value
        },
        yAxis: {
            type: 'value'
        },
        tooltip: {
            trigger: 'item'
        },
        series: [{
            data: optionData.value,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
            },
            itemStyle: {
                normal: {
                    label: {
                        show: true, //开启显示
                        position: 'top', //在上方显示
                        textStyle: { //数值样式
                            color: 'black',
                            fontSize: 12
                        }
                    }
                }
            },
        }]
    };
    myChart.setOption(option);
};

onMounted(() => {
    // 初始化或重置图表
    if (eventBus.state.averageScores.length) {
        convertType(eventBus.state.averageScores);
        nextTick(() => {
            initChart();
        });
    }
});
</script>

<style lang="scss" scoped>
 .container {
     display: flex;
     justify-content: center;
     align-items: center;
     width: 230px;
     height: 40px;
     background-color: #94c1f3;
     border-bottom: 2px solid #4f2e06;
     border-radius: 5px;
     margin-left: 20px;

     img {
         margin:3px 0px 0px -112px;
         width: 49px;
         height: 39px;
     }

     .tag {
         text-align: center;
         color: white;
     }
 }

</style>